package demo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerFile {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream is = null;
        FileOutputStream fos = null;
        OutputStream outputStream = null;
        try {
            //1、获取一个连接地址和指定的端口号
            serverSocket = new ServerSocket(9900);
            //2. 等待着客户端的链接
            accept = serverSocket.accept();
            //3.读取客户端的消息。输入流
            is = accept.getInputStream();

            //4.文件输出
            fos = new FileOutputStream(new File("tests.jpg"));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = is.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }
            //5.通知客户端接受完毕
            outputStream = accept.getOutputStream();
            outputStream.write("接受完毕，可以关闭连接了".getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //6.关闭资源
            if (outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    //关闭输入流
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (accept != null) {
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
